#include "XIceApp.h"

namespace Xts
{
	namespace IceRuntime
	{
		XIceApp::XIceApp(const std::string& configPath)
			:x_pIc(NULL), x_pLogger(NULL)
		{
			if(configPath.length() != 0)
			{
				Ice::PropertiesPtr pProperties = Ice::createProperties();
				try
				{
					pProperties->load(configPath); 
					Ice::InitializationData initData;
					initData.properties = pProperties;
					x_pIc = Ice::initialize(initData);
					x_pLogger = x_pIc->getLogger();
					x_pLogger->print("Initialize Ice.Communicator with configuration:" + configPath);
				}
				catch(const Ice::Exception& ex)
				{
					x_pIc = Ice::initialize();
					x_pLogger = x_pIc->getLogger();
					x_pLogger->error(ex.what());
					x_pLogger->print("Initialize Ice.Communicator with default");
				}
			}
			else
			{
				x_pIc = Ice::initialize();
				x_pLogger = x_pIc->getLogger();
				x_pLogger->print("Initialize Ice.Communicator with default");
			}			
		}

		XIceApp::~XIceApp(void)
		{
			if(x_pIc != NULL)
			{
				x_pIc->destroy();
			}
		}

		bool XIceApp::InitObjectAdapter(const std::string& adapterName, const std::string& endPnts)
		{
			if(adapterName.length() == 0)
			{
				x_pLogger->error("Can't create Ice.ObjectAdapter without a name");
				return false;
			}

			Ice::ObjectAdapterPtr pObjAdapter;

			if(endPnts.length() == 0)
			{
				try
				{
					pObjAdapter = x_pIc->createObjectAdapter(adapterName);
					x_objectAdapterSet[adapterName] = pObjAdapter;
					return true;
				}
				catch(const Ice::Exception& ex)
				{
					x_pLogger->error(ex.what());
					return false;
				}
			}
			else
			{
				try
				{
					pObjAdapter = x_pIc->createObjectAdapterWithEndpoints(adapterName, endPnts);
					x_objectAdapterSet[adapterName] = pObjAdapter;
					return true;
				}
				catch(const Ice::Exception& ex)
				{
					x_pLogger->error(ex.what());					
				}
			}
			return false;

		}

		Ice::CommunicatorPtr XIceApp::RetrieveCommunicator()
		{
			return x_pIc;
		}

		Ice::LoggerPtr XIceApp::RetrieveLogger(const std::string& prefix)
		{
			if(prefix.length() == 0)
				return x_pLogger;
			return x_pLogger->cloneWithPrefix(prefix);
		}

		std::vector<std::string> XIceApp::RetrieveAdapterNames()const
		{
			std::vector<std::string> adapterNames;
			std::map<std::string, Ice::ObjectAdapterPtr>::const_iterator cIter;
			for(cIter = x_objectAdapterSet.cbegin(); cIter != x_objectAdapterSet.cend(); cIter++)
			{
				adapterNames.push_back(cIter->first);
			}
			return adapterNames;
		}

		Ice::ObjectAdapterPtr XIceApp::RetrieveObjectAdapter(const std::string& adapterName)
		{
			if(x_objectAdapterSet.find(adapterName) == x_objectAdapterSet.end())
				return NULL;
			return x_objectAdapterSet[adapterName];
		}
	}
}

